package com.example.wanandroid.activity;

import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.widget.Toast;

import com.example.wanandroid.R;
import com.example.wanandroid.adapter.NavigationAdapter;
import com.example.wanandroid.adapter.SearchAdapter;
import com.example.wanandroid.base.BaseActivity;
import com.example.wanandroid.constant.Constant;
import com.example.wanandroid.entity.SearchBean;
import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;
import com.kymjs.rxvolley.toolbox.Loger;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class SearchActivity extends BaseActivity {

    RecyclerView mRecyclerView;
    private List<SearchBean> mList = new ArrayList<>();
    SearchAdapter searchAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        initData();
        initView();
    }

    private void initView() {
        mRecyclerView = findViewById(R.id.mRecyclerView);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));
        searchAdapter=new SearchAdapter(this,mList);
        mRecyclerView.setAdapter(searchAdapter);

        searchAdapter.setOnItemClickListener(new NavigationAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position) {
                Toast.makeText(SearchActivity.this, position+"", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void initData() {
        //get请求简洁版实现
        RxVolley.get(Constant.SEARCH_HOT, new HttpCallback() {
            @Override
            public void onSuccess(String data) {
                Loger.debug("请求到的数据:" + data);
                if (!TextUtils.isEmpty(data)) {
                    GetSearchJson(data);
                }
            }
        });
    }

    private void GetSearchJson(String data) {
        try {
            JSONObject jsonObject = new JSONObject(data);
            JSONArray jsonArray = jsonObject.getJSONArray("data");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonData = (JSONObject) jsonArray.get(i);
                SearchBean searchBean = new SearchBean();
                searchBean.setName(jsonData.getString("name"));
                mList.add(searchBean);
                searchAdapter.notifyDataSetChanged();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
